/*
 * @Author: huangtianyang 916072572@qq.com
 * @Date: 2022-12-02 17:04:14
 * @LastEditors: huangtianyang
 * @LastEditTime: 2023-11-14 09:25:07
 * @FilePath: \cxl-admin\src\store\user.store.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { routerStore } from './router.store'
import { login as loginApi } from '@/apis/login/login'
import { storage } from './sessionStorage'
import { CountDown } from '@/utils'

export const userStore = defineStore('user', {
    state() {
        return {
            token: '',
            company: '',
            companyId: '',
            customerNo: '',
            name: '',
            userId: '',
            phone: '',
            isSuperAdmin: false,
            _routerStore: routerStore(),
            permission: true
        }
    },
    actions: {
        resetData() {
            this.token = ''
            this.company = ''
            this.companyId = ''
            this.customerNo = ''
            this.userId = ''
            this.isSuperAdmin = false
            this.phone = ''
            this.permission = true
            this.name = ''
        },
        /**
         * 保存token
         * @param token
         */
        setToken(token: string) {
            this.token = token

            //缓存token 判断token是否为空，为空则删除本地缓存
            token ? storage.set('token', token) : storage.remove('token')
        },

        /**
         * 调用登录接口
         * @param phone
         * @param password
         * @returns
         */
        async login(phone: string, password: string) {
            return new Promise((resolve, reject) => {
                loginApi(phone, password).then((res: any) => {
                    if (res.data.value === 200) {
                        resolve(res.data)
                        this.setToken(res.data.data.accessToken)
                        storage.set('loginTime', new Date().getTime().toString())
                        storage.set('refreshToken', res.data.data.refreshToken)
                        //提前5s获取token
                        storage.set('expire', (res.data.data.expire - 5000).toString())
                        //倒计时请求刷新token
                        new CountDown((res.data.data.expire - 5000) / 1000).start(() => {
                            console.log('开始请求刷新token')
                        })
                    } else {
                        reject(res.data)
                    }
                })
            })
        }
    }
})
